<?php

namespace plugin\agent\app\admin\logic;

use app\common\logic\BaseLogic;
use app\model\pms\Goods;
use plugin\agent\app\api\logic\GoodsSearchLogic;
use plugin\agent\app\model\AgentGoods;
use plugin\agent\app\model\AgentRule;
use support\utils\Time;

class AgentGoodsLogic extends BaseLogic
{
    public function __construct()
    {
        $this->model = new AgentGoods();
    }

    public function delAgentGoods($goods_ids)
    {
        $extGoodsIds = $this->model->where('goods_id', 'in', $goods_ids)->column('goods_id');
        $newIds = [];
        foreach ($goods_ids as $id) {
            if (in_array($id, $extGoodsIds)) {
                $newIds[] = $id;
            }
        }
        if (!$newIds) {
            return;
        }
        GoodsSearchLogic::addGoodsChange($newIds);
        Goods::where('id', 'in', $newIds)->update(['is_agent' => 0]);
        $this->model->where('goods_id', 'in', $newIds)->delete();
    }

    public function joinAgentGoods($goods_ids)
    {
        $insert = [];

        $extGoodsIds = $this->model->where('goods_id', 'in', $goods_ids)->column('goods_id');
        $newIds = [];
        foreach ($goods_ids as $id) {
            if (!in_array($id, $extGoodsIds)) {
                $newIds[] = $id;
            }
        }
        if (!$newIds) {
            return;
        }
        GoodsSearchLogic::addGoodsChange($newIds);

        $rule_id = AgentRule::where([
            'status' => 1,
            'is_default' => 1,
        ])->value("id");
        if (!$rule_id) {
            $rule_id = AgentRule::where([
                'status' => 1,
            ])->value("id");
        }
        foreach ($newIds as $goods_id) {
            $insert[] = [
                'goods_id' => $goods_id,
                'rule_id' => $rule_id,
                'type' => 1,
                'create_time' => Time::now(),
                'update_time' => Time::now(),
            ];
        }
        Goods::where('id', 'in', $newIds)->update(['is_agent' => 1]);
        $this->model->insertAll($insert);
    }

    public function updateAgentGoods($input)
    {
        $update = [
            'type' => $input['type'],
            'rule_id' => $input['rule_id'],
            'one_rate' => $input['type'] == 1 ? 0 : $input['one_rate'],
            'two_rate' => $input['type'] == 1 ? 0 : $input['two_rate'],
            'three_rate' => $input['type'] == 1 ? 0 : $input['three_rate'],
            'update_time' => Time::now(),
        ];

        $this->model->update($update, [
            'id' => $input['id']
        ]);
    }

}